<?php
class MenusController extends AppController{
	public $helpers = array('Html', 'Form');
	public $components = array('Session');
	
	public function beforeFilter() {
		$this->Auth->deny('index');
	}
	
	public $paginate = array(
        'limit' => 10,
    );
	
	function index(){
		$base_url = 'http://'.$_SERVER['HTTP_HOST'].$this->base;
		$this->set('title_for_layout', 'Menu');
		
		$menus = $this->Menu->find('all');
		
		$menus_with_parent_name = $this->Menu->find_parent_menu($menus);
		
		//$this->set('menus',$menus_with_parent_name);
		$tree = $this->Menu->menu_tree();
		$detailes_menus = $this->Menu->menu_detailes($tree,$base_url);
		$this->set('menus',$detailes_menus);
	}
	
	function add(){
		$this->set('title_for_layout', 'Create Menu');
		
		$parent_menu = $this->Menu->parent_menu();
		$this->set('menus', $parent_menu);
		$this->set('menu_id', $id);
		$this->set('total', $this->Menu->find('count') + 1);
		
		if ($this->request->is('post')) {
			$this->request->data['Menu']['user_id'] = $this->Auth->user('id'); //Added this line 
			
			if ($this->Menu->save($this->request->data)) {
				$this->Session->setFlash('Your post has been saved.');
				$this->redirect(array('action' => 'index'));
			}
		}
	}
	
	function edit($id = null){
		$this->set('title_for_layout', 'Edit Menu');
	
		$this->Menu->id = $id;
		$this->set('menus', $this->Menu->find('all'));
		$this->set('total', $this->Menu->find('count'));
		
		if ($this->request->is('get')) {
			$this->request->data = $this->Menu->read();
		} else {
		
			if ($this->Menu->save($this->request->data)) {
				$this->Session->setFlash('Your post has been updated.');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('Unable to update your post.');
			}
		}
	
	}
	
	function delete($id){
		
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}
		
		if ($this->Menu->delete($id)) {
			$this->Session->setFlash('The menu with id: ' . $id . ' has been deleted.');
			$this->redirect(array('action' => 'index'));
		}
		
	}
	
	public function isAuthorized($user) {
		// All registered users can add posts
		if ($this->action === 'add') {
			return true;
		}
		
		if ($this->action === 'index') {
			
			if (isset($user['role']) && $user['role'] === 'admin') {
				return true;
			}else{
				$this->Session->setFlash('You are not authorised user');
				$this->redirect('/users/login/');
			}
		}
		
		
		// The owner of a post can edit and delete it
		if (in_array($this->action, array('edit', 'delete'))) {
			$menuId = $this->request->params['pass'][0];
			if ($this->Menu->isOwnedBy($menuId, $user['id'])) {
				return true;
			}else{
				return false;
			}
		}

		return parent::isAuthorized($user);
	}
	
}
?>